<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
    <script th:src="@{/js/jquery-3.4.0.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.js}"></script>
    <script th:src="@{/js/bootstrap.js}"></script>
    <style type="text/css">
        body {
            font-family: monospace;
            font-size: 16px;
            /*width: 100vw;*/
            /*height: 100vh;*/
            /*opacity: 0.4;*/
            /*background-image: url(/img/background_1.jpg);*/
            /*background-size: cover;*/
        }

        .single-bg {
            background-image: url(/img/background_1.jpg);
            background-color: #fff;
            background-size: cover;
            width: 100vw;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
        }

        .single-bg:after {
            content: "";
            position: fixed;
            width: 100vw;
            height: 100vh;
            top: 0;
            left: 0;
            background: rgba(246,246,246,.9);
        }

        .main {
            top: 50%;
            left: 50%;
            width: 940px;
            height: 480px;
            position: absolute;
            margin-top: -240px;
            margin-left: -470px;
            background-color: #ffffff
        }
</style>
    <script th:inline="javascript">

        // 检查用户名
        function checkName() {
            let name = $("#username");
            let value = name.val();
            let regex = /^[a-zA-Z]/;
            let len = value.length;
            // 检查长度
            if (len < 4 || len > 10) {
                fail(name, "字母开头，长度4-10个字符！");
                return;
            }
            // exec 查找并返回当前的匹配结果，并以数组的形式返回。
            // 检查昵称
            if (!regex.exec(value)) {
                fail(name, "请以字母开头！");
                return;
            }
            name.attr("class", "form-control is-valid");
            return value;
        }

        // 验证姓名，长度2-4字
        function checkRealName() {
            let realName = $("#realName");
            let value = realName.val();
            //let len = value.length;
            let regex = /^[\u4E00-\u9FA5]{2,4}$/;
            if (!regex.exec(value)) {
                fail(realName, "请输入长度2-4字的中文名！");
                return;
            }
            realName.attr("class", "form-control is-valid");
            return value;
        }

        // 检查密码
        function checkPass() {
            let pass = $("#password");
            let value = pass.val();
            let len = value.length;
            let regex = /(.*[a-zA-z].*)+(.*[0-9a-zA-z].*)+/;
            // 限制长度
            if (len < 8 || len > 20) {
                fail(pass, "密码长度为8-20！");
                return;
            }
            // test() 返回 Boolean，查找对应的字符串中是否存在模式
            if (!regex.test(value)) {
                fail(pass, "密码至少8位，包含字母、数字");
                return;
            }
            pass.attr("class", "form-control is-valid");
            return value;
        }

        // 确认密码
        function checkPass2() {
            let pass = $("#password");
            let value = pass.val();
            let pass2 = $("#rePassword");
            let value2 = pass2.val();
            if (value.length === 0 || value2.length === 0) {
                fail(pass2, "请输入确认密码！");
                return;
            }
            if (!(value === value2)) {
                fail(pass2, "两次密码输入不一致！");
                return;
            }
            pass2.attr("class", "form-control is-valid");
            return value;
        }

        // 检查号码
        function checkPhone() {
            let phone = $("#phoneNum");
            let value = phone.val();
            let regex = /^1[3-9]\d{9}$/;
            if (!regex.test(value)) {
                fail(phone, "请输入有效的手机号码！");
                return;
            }
            phone.attr("class", "form-control is-valid");
            return value;
        }

        // 校验邮箱
        function checkEmail() {
            let email = $("#email");
            let value = email.val();
            // 字母数字开头，中间可以有_或-，@后面是字母数字，.后面跟字母
            let regex = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
            if (!regex.test(value)) {
                fail(email, "请输入合法的邮箱地址！")
                return;
            }
            email.attr("class", "form-control is-valid");
            return value;
        }

        // 验证码校验
        function checkCode() {
            let code = $("#randomCode");
            let value = code.val();
            console.log("校验验证码，值：" + value);
            let regex = /[a-zA-Z0-9]{4}/;
            if (value.length > 4) {
                fail(code);
                return;
            }
            if (!regex.exec(value)) {
                fail(code);
                return;
            }
            code.attr("class", "form-control");
            return value;
        }

        // 规范操作：清空文本，获得焦点，样式提示
        function fail(obj, str) {
            obj.val("");
            obj.focus();
            obj.attr("placeholder", (str == null ? "重新输入！" : str));
            obj.attr("class", "form-control is-invalid");
        }


        /**
         * ready()方法：当 DOM（文档对象模型） 已经加载，并且页面（包括图像）已经完全呈现时，会发生 ready 事件。
         * 语法1：$(document).ready(function)
         * 语法2：$().ready(function)
         * 语法3：$(function)
         */
        // [jq] 点击注册按钮事件
        $(document).ready(function () {
            $("#registerBtn").click(function () {
                let user = {};
                let userDO = {};
                // 1、检查并获取字段
                userDO.username = checkName();
                if (userDO.username == null) {
                    return;
                }
                if (checkPass() == null) {
                    return;
                }
                userDO.password = checkPass2();
                if (userDO.password == null) {
                    return;
                }
                userDO.realName = checkRealName();
                if (userDO.realName == null) {
                    return;
                }
                userDO.gender = $("input[name='gender']:checked").val();
                if (userDO.gender == null) {
                    return;
                }
                userDO.email = checkEmail();
                if (userDO.email == null) {
                    return;
                }
                userDO.phoneNum = checkPhone();
                if (userDO.phoneNum == null) {
                    return;
                }
                // 封装验证码
                user.randomCode = checkCode();
                if (user.randomCode == null) {
                    return;
                }
                user.userDO = userDO;
                console.log(userDO);

                $.ajax({
                    url: "/user/register",
                    type: "post",
                    data: JSON.stringify(user),
                    contentType: "application/json;charset=UTF-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        console.log(data.code);
                        if (data.code === 1003) {
                            alert("验证码错误，请重新输入！");
                            let code = $("#randomCode");
                            fail(code);
                        }
                        if (data.code === 1002) {
                            alert("该手机号码已被注册！");
                            let phoneNum = $("#phoneNum");
                            fail(phoneNum, "换一个号码~")
                        }
                        if (data.code === 1001) {
                            alert("这个用户名太抢手，换一个吧~");
                            let username = $("#username");
                            fail(username, "字母开头，4-10个字符");
                        }
                        if (data.code === 500) {
                            alert("服务器繁忙，请稍后再试！");
                        }
                        if (data.code === 200) {
                            alert("注册成功，快去登录吧~");
                            window.location.href = "/sign_in";
                        }
                    }
                });
            });
        });

        // 刷新验证码（随机数模仿时间戳，防止缓存）
        function refreshCode() {
            $("#code").attr("src", "/randomCode?" + Math.random());
        }

    </script>
</head>
<!-- 由于使用thymeleaf模板引擎，修改url为如下 -->
<body>
<!--<div class="container-fluid" style="background-color: red">-->
<div class="single-bg"></div>
<div class="main border rounded shadow">
    <div style="width: 520px; margin: 0 auto; padding: 30px 0">
        <h1 style="text-align: center;">Beehive 注册</h1>
        <hr>
    </div>
    <form style="display: block; width: 800px; margin: 0 auto" method="post" action="/user/">
        <table>
            <tr>
                <td>
                    <div class="form-group row" style="margin-right: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px">用&#8194;户&#8194;名&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="text" class="form-control" id="username"
                                   placeholder="以字母开头，6-10个字符" onchange="checkName()">
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group row" style="margin-left: 10px;">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px">姓&#12288;&#12288;名&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="text" class="form-control" id="realName" placeholder="姓名"
                                   onchange="checkRealName()">
                        </div>
                    </div>
                </td>
            </tr>

            <tr>
                <td>
                    <div class="form-group row" style="margin-right: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px; width: 36px">密&#12288;&#12288;码&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="password" class="form-control" id="password" placeholder="密码，长度8-20"
                                   onchange="checkPass()">
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group row" style="margin-left: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px">性&#12288;&#12288;别&#12288;&#32;</span>
                        </label>
                        <div class="custom-control custom-radio custom-control-inline" style="padding-top: 8px;">
                            <input type="radio" id="male" name="gender" class="custom-control-input" value="1"
                                   checked>
                            <label class="custom-control-label" for="male">&#8194;男&#12288;</label>
                        </div>
                        <div class="custom-control custom-radio custom-control-inline" style="padding-top: 8px;">
                            <input type="radio" id="female" name="gender" class="custom-control-input" value="0">
                            <label class="custom-control-label" for="female">&#8194;女&#12288;</label>
                        </div>
                    </div>
                </td>
            </tr>

            <tr>
                <td>
                    <div class="form-group row" style="margin-right: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px; width: 36px">确认密码&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="password" class="form-control" id="rePassword" placeholder="请再次确认密码"
                                   onchange="checkPass2()">
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group row" style="margin-left: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px; width: 36px">手机号码&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="text" class="form-control" id="phoneNum" placeholder="手机号码"
                                   onchange="checkPhone()">
                        </div>
                    </div>
                </td>
            </tr>

            <tr>
                <td>
                    <div class="form-group row" style="margin-right: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px; width: 36px">电子邮箱&#12288;&#32;</span>
                        </label>
                        <div style="width: 277px;">
                            <input type="email" class="form-control" id="email" placeholder="电子邮箱"
                                   onchange="checkEmail()">
                        </div>
                    </div>
                </td>
                <td>
                    <div class="form-group row" style="margin-left: 10px">
                        <label class="col-form-label">
                            <span style="color: red">*</span>
                            <span style="margin-right: 10px">验&#8194;证&#8194;码&#12288;&#32;</span>
                        </label>
                        <div style="width: 120px;">
                            <input type="text" class="form-control" id="randomCode" placeholder="验证码"
                                   onchange="checkCode()">
                        </div>
                        <div style="margin-left: 22px">
                            <img id="code" th:src="@{/randomCode}" height="38px" class="rounded" title="看不清？换一张"
                                 onclick="refreshCode()"/>
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div style="margin: 10px 190px 0">
                        <button type="button" class="btn" id="registerBtn"
                                style="width: 100%; background-color: #38b4e6; border-color: #38b4e6;
                                            height: 40px; color: #FFF; font-family: monospace; font-size: 18px">
                            注册
                        </button>
                    </div>
                </td>
            </tr>
        </table>
    </form>
</div>
<!--</div>-->
</body>
</html>